Equality

There are different ways to compare things in Go, none of them is perfect.

Operators == and !=#

The equality operator is the simplest and often most efficient way to compare things in Go, but it only works on certain things. Most notably it doesn’t work on slices or maps. Slices and maps can only be compared to nil this way.

Comparison

Using == you can compare basic types like int and string, and also arrays and structs that have elements in them that can themselves be compared using ==:

Using `==` to compare structs

As soon as you add a property to the struct that can’t be compared with ==, you need a whole other way to compare:

Slices can't be compared using `==`

Writing specialized code#

If performance is important and you need to compare slightly more complicated types, your best bet might be comparing manually:

Manually comparing complicated types

reflect.DeepEqual#

DeepEqual is the most generic way to compare things in Go, and it can handle most of the things. Here is the catch:

Using `DeepEqual` for comparison

DeepEqual is 100 times slower in this example than writing manual code for comparing that struct.

Note that DeepEqual will compare unexported (lowercased) fields from a struct as well. Also, two different types would never be considered deeply equal even if they were two different structs with identical fields and values.

Uncomparable things#

Mismatch things

Some things can’t be compared and are considered unequal even to themselves, such as floating-point variables with a NaN value or a func type. If you have such fields in a struct for instance, the struct won’t be DeepEqual to itself:

Comparing variables with a `NaN` value

bytes.Equal#

bytes.Equal is a specialized way to compare byte slices. It’s much faster than simply comparing two slices with a for loop. Something worth being aware of, the bytes.Equal function considers empty and nil slices to be equal, while reflect.DeepEqual does not.

Inheritance

Exercise: Comparing Structs